import { Upload, GetProp, message, Modal, Spin } from 'antd';
import React from 'react';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiInterceptors, getApplogoList, uploadAppLogo, } from '@/client/api';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Icon, { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import styles from '../styles.module.css';
import { logoUrl } from '@/utils';
import { userUpdate } from '@/client/api/login';
import { ChatContext } from '@/app/chat-context';
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error(t('uploadLimitDesc'));
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error(t('uploadSizeDesc') + '2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const UpdateAvatarModal: React.FC<{
  open: boolean;
  onCancel: () => void;
  type?: 'add' | 'edit';
}> = ({ open, onCancel, type = 'add', }) => {
  const { userInfo, handleUserInfoChange } = useContext(ChatContext);
  const { t, i18n } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange = async (info) => {
    setLoading(true);

    const formData = new FormData();
    formData.append('image_file', info.file)
    const [, res] = await apiInterceptors(uploadAppLogo({ type: 1, file: formData }));
    if (res) {
      setImageUrl(logoUrl + res)
      setSelectedAvatar(res);
      setLoading(false);
    } else {
      setLoading(false);
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
    </div>
  );
  const [recommendedAvatars, setRecommendedAvatars] = useState([])
  const [selectedAvatar, setSelectedAvatar] = useState('');

  const handleAvatarSelect = (avatarUrl: string) => {
    setSelectedAvatar(avatarUrl.id);
  };
  const onOk = async () => {
    if (!selectedAvatar) {
      message.error(t('selectAvatar'));
      return;
    }
    const params = {
      avatar_id: selectedAvatar,
      id: userInfo.user_no,
    }
    const [_, data] = await apiInterceptors(userUpdate(params));
    if (data) {
      const user = {
        ...userInfo,
        ...data,
      }
      handleUserInfoChange(JSON.stringify(user));
    }
    onCancel();
  }

  // 系统推荐头像
  const initSysLogos = useCallback(async () => {
    const [_, data] = await apiInterceptors(getApplogoList(1));
    const list = data.map((item) => { return { url: logoUrl + item, id: item } });
    setRecommendedAvatars(list)
  }, []);

  useEffect(() => {
    initSysLogos()
  }, [initSysLogos])


  return <Modal title={t('ModifyAvatar')} open={open} onOk={onOk} className={styles['extra-container']}
    onCancel={onCancel}>
    <Spin spinning={loading}>
      <div className='p-3 flex flex-col'>
        <div>{t('SystemRecommendedAvatars')}</div>
        <div className="avatar-list flex flex-wrap gap-2 mt-3 h-40 overflow-y-scroll">
          {recommendedAvatars.map((avatarUrl, index) => (
            <Image
              src={avatarUrl.url}
              alt=""
              width={75}
              height={75}
              key={index}
              className={`cursor-pointer border  ${selectedAvatar === avatarUrl.id ? 'border-[#8665FF] dark:border-[#8665FF]' : 'border-[#d5e5f6] dark:border-[#ffffff66]'}`}
              onClick={() => handleAvatarSelect(avatarUrl)}
            />
          ))}
        </div>
        <div className='flex gap-3 my-3'>
          <div>{t('CustomizeAvatar')}</div>
          <div>
            <Upload name="avatar" listType="picture-card"
              beforeUpload={beforeUpload}
              customRequest={handleChange}
              showUploadList={false}
              maxCount={1}
              multiple={false}
              className='avatar-uploader'
              accept='.png,.jpeg'
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: 75, height: 75 }} /> : uploadButton}
            </Upload>
            <div className='mt-3'>{t('UploadDesc')}</div>
          </div>
        </div>
      </div>
    </Spin>
  </Modal>
}
export default UpdateAvatarModal;